package com.foreknow.filter;

import com.sun.javafx.binding.StringFormatter;

import javax.servlet.*;
import java.io.IOException;

/**
 * 转换字符编码的过滤器(Filter)
 */
public class CharactorEncodingFilter implements Filter {
    private FilterConfig filterConfig;
    private String encoding = "ISO8859-1";

    @Override
    public void init(FilterConfig filterConfig) throws ServletException {
        this.filterConfig = filterConfig;
        encoding = filterConfig.getInitParameter("encode");// utf-8
    }

    @Override
    public void doFilter(ServletRequest req, ServletResponse resp, FilterChain filterChain) throws IOException, ServletException {
        req.setCharacterEncoding(encoding);
        resp.setContentType("text/html;charset=utf-8");
        // 如果还有下一个过滤器，就要讲这个请求交给下一个过滤
        // 如果没有，就将请求交给servlet来处理
        filterChain.doFilter(req,resp);
    }

    @Override
    public void destroy() {
        filterConfig = null;
    }
}
